<!-- 上传文件携带值 -->
<template>
  <el-upload
    class="upload-demo"
    action=""
    :limit="1"
    :accept="acceptType"
    :http-request="handleUpload"
    :before-upload="beforeUpload"
    :on-change="changeHandle"
    :show-file-list="false"
  >
    <template #trigger>
      <template v-if="!fileName">
        <el-button type="primary" style="margin-right: 10px">选择文件</el-button>
        <div class="el-upload__tip text-red">*只能上传一个文件</div>
      </template>
      <template v-else>
        <div class="el-upload__tip text-red">{{ fileName }}</div>
      </template>
    </template>
  </el-upload>
</template>

<script setup>
import { ref, toRaw, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { fileList } from '@/api'
import { getAcceptByType } from '@/utils/public'
const props = defineProps({
  // 上传保存的目录
  uploadDirName: {
    type: String,
    default: ''
  },
  // 传入文件类型，如：'image'、'video'、'audio'、'word'、'excel'、'ppt'、'pdf'、'zip'
  fileType: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['colse'])
// 文件名
// eslint-disable-next-line vue/no-dupe-keys
const fileName = ref('')
const acceptType = ref('*')
watch(
  () => props.fileType,
  (val) => {
    if (val) {
      acceptType.value = getAcceptByType(val)
    }
  },
  {
    deep: true,
    immediate: true
  }
)

// 文件类型验证
const beforeUpload = (rawFile) => {
  if (props.uploadDirName === '') {
    return false
  }
  if (props.fileType !== '') {
    const arr = acceptType.value.split(',').map((item) => item.trim().replace('.', ''))
    let flag = false
    arr.forEach((item) => {
      if (new RegExp(`\\b${item}\\b`, 'gi').test(toRaw(rawFile).name)) {
        flag = true
      }
    })
    if (!flag) {
      ElMessage.error(`请上传${getAcceptByType(props.fileType)}格式的文件！`)
      return false
    }
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 10
  if (!isLt2M) {
    ElMessage.error('上传的文件大小不能超过10MB!')
    return false
  }
  return isLt2M
}
// 选择文件时赋值文件名
const changeHandle = (file) => {
  if (props.uploadDirName === '') {
    ElMessage.error('请先选择上传目录!')
    return
  }
  fileName.value = file.name
}
// 上传接口
const handleUpload = async (file) => {
  const formData = new FormData()
  formData.append('file', toRaw(file.file))
  formData.append('directory', props.uploadDirName)
  const res = await fileList.uploadFile(formData)
  if (res) {
    ElMessage.success(`${file.file.name}文件上传成功`)
    setTimeout(() => {
      emit('colse')
    }, 1000)
  }
}
</script>

<style lang="scss" scoped>
.view-file-name {
  color: var(--el-text-color-regular);
  font-size: 12px;
  margin-top: 7px;
}
.text-red {
  color: red;
}
</style>
